﻿Option Strict On
Imports Microsoft.VisualBasic
Imports System.Text.RegularExpressions
Imports dooll.Config
Imports dooll.Common
Imports System.IO
Imports Newtonsoft.Json
Namespace UI


    Public Class MasterPage
        Inherits IPage
        Private Const _USER As String = "__CityFly__"
        Private mAdmin As AdminInfo

        Protected ReadOnly Property Admin() As AdminInfo
            Get
                If mAdmin Is Nothing Then
                    If Session.Item(_USER) Is Nothing Then
                        Dim tokenValue As String = Request.QueryString("Token")
                        If String.IsNullOrEmpty(tokenValue) OrElse Not tokenValue = "$Token$" Then
                            mAdmin = New AdminInfo
                        Else
                            If Not LoadToken(tokenValue) Then
                                mAdmin = New AdminInfo
                            End If
                        End If
                    Else
                        Try
                            mAdmin = CType(Session.Item(_USER), AdminInfo)

                        Catch ex As Exception
                            mAdmin = New AdminInfo
                        End Try
                    End If
                End If
                Return mAdmin
            End Get
        End Property

        ''' <summary>
        ''' 读取令牌
        ''' </summary>
        ''' <param name="tokenValue"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Protected Overrides Function LoadToken(ByVal tokenValue As String) As Boolean
            Dim returnValue As Boolean = False
            If Not String.IsNullOrEmpty(tokenValue) Then '持有令牌

                '调用WebService获取主站凭证
                Dim tokenService As New adminpassport.TokenService

                Dim tokenInfo As String = CStr(tokenService.TokenGetCredence(tokenValue))

                If Not String.IsNullOrEmpty(tokenInfo) Then
                    Try
                        mAdmin = CType(JavaScriptConvert.DeserializeObject(tokenInfo, GetType(AdminInfo)), AdminInfo)
                        Session.Item(_USER) = mAdmin
                        Return True
                    Catch ex As Exception
                        Return False
                    End Try


                End If
            End If

            Return False
        End Function

        ''' <summary>
        ''' 检查权限
        ''' </summary>
        ''' <remarks></remarks>
        Protected Overrides Sub ChkACL()
            If LabelInfo.ACL = ACL.Admin Then
                If Not Admin.IsLogin Then
                    ShowDenyMessage()
                    Response.End()
                Else
                    Return
                End If
            End If
            MyBase.ChkACL()
        End Sub

        ''' <summary>
        ''' 显示未授权信息
        ''' </summary>
        ''' <remarks></remarks>
        Protected Overrides Sub ShowDenyMessage()
            If String.IsNullOrEmpty(AppConfigInfo.AdminLoginPage) Then
                Response.Write(Util.ReturnValue("403", "你还未登录系统!!!"))
            Else
                If Not IsXmlHttp Then
                    Dim toUrl As String = AbsoluteUri
                    Response.Redirect(String.Concat(AppConfigInfo.AdminLoginPage, "?toUrl=", Server.UrlEncode((toUrl))))
                Else
                    Response.Write(Util.ReturnValue("403", "你还未登录系统!!!"))
                End If
            End If
        End Sub

        Protected Overrides Function ChkLabelItemACL(ByVal acl As String, ByVal fnKey As String, ByRef ErrMessage As String, ByVal RequestObj As NameValueCollection) As Boolean
            If acl = "3" Then
                If Not ChkAdminRights(LabelInfo.MID, "ACL_Run") Then
                    ErrMessage = String.Format("{0},对不起!!你的帐号没有({3})权限[{2}({1})].", 403, fnKey, tHtmlFile, "ACL_Run")
                    Return False
                Else
                    Return True
                End If
            End If

            Dim Rights As String() = Split(acl, "|")
            If Rights.Length = 2 AndAlso Rights(0) = "3" Then
                If Not ChkAdminRights(LabelInfo.MID, Rights(1)) Then
                    ErrMessage = String.Format("{0},对不起!!你的帐号没有({3})权限[{2}({1})].", 403, fnKey, tHtmlFile, Rights(1))
                    Return False
                Else
                    Return True
                End If
            Else
                Return MyBase.ChkLabelItemACL(acl, fnKey, ErrMessage, RequestObj)
            End If


            Return True
        End Function

        REM 检验管理员权限
        Protected Function ChkAdminRights(ByVal fnMenuHtmlFile As String, ByVal fnAct As String) As Boolean
            Return Admin.ChkWebRights(IO.Path.GetFileName(fnMenuHtmlFile), fnAct)
        End Function

        REM 检验管理员权限
        Protected Function ChkAdminRights(ByVal fnMenuID As Integer, ByVal fnAct As String) As Boolean
            If fnMenuID = 0 And Admin.IsLogin Then
                Return True
            End If
            Return Admin.ChkWebRights(fnMenuID, fnAct)
        End Function

        REM 重写ReplaceRequestString
        Protected Overrides Function ReplaceLoginString(ByRef sb As StringBuilder) As String
            Dim fnMatchs As MatchCollection = Regex.Matches(sb.ToString(), "{admin:(?'2'\w+):?(?'3'\w*)}", RegexOptions.IgnoreCase Or RegexOptions.Compiled)
            Dim tmpStr As String = String.Empty

            For Each m As Match In fnMatchs
                Try
                    tmpStr = Admin.getProperty(m.Groups.Item(2).Value)
                Catch ex As Exception
                    tmpStr = String.Empty
                End Try
                sb.Replace(m.Value, StringFilter(tmpStr))
            Next
            fnMatchs = Nothing
            MyBase.ReplaceLoginString(sb)
            Return sb.ToString
        End Function

        Private Sub Page_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
            mAdmin = Nothing
        End Sub

        REM 登录系统函数,fnUserName 用户名,fnPassword 密码
        Protected Overrides Function Login(ByVal fnUserName As String, ByVal fnPassword As String, token As String) As String

            If String.IsNullOrEmpty(fnUserName) OrElse String.IsNullOrEmpty(fnPassword) Then Return Util.ReturnValue("101", "请先填写用户名和密码(长度不够)!")

            Try
                Dim AM As New AdminManage(UriKey)

                mAdmin = AM.Login(fnUserName, fnPassword, Request.ServerVariables("REMOTE_ADDR"))
                If Not mAdmin.IsLogin Then
                    Return Util.ReturnValue("-1", AM.ErrMessage)
                Else
                    Session.Item(_USER) = mAdmin

                    If Request.Cookies("siteid") Is Nothing OrElse String.IsNullOrEmpty(Request.Cookies("siteid").Value) Then
                        Dim r As HttpCookie = New HttpCookie("siteid", CStr(mAdmin.Item("siteid")))
                        Response.Cookies.Add(r)
                    End If
                    Return Util.ReturnValue("0", "登录成功")
                End If
                AM = Nothing
            Catch ex As Exception
                Return Util.ReturnValue("-100", ex.Message)
            End Try

        End Function

        Protected Sub CheckAdminLoginStatus()
            If Not Admin.IsLogin Then
                Response.Clear()
                Response.Write(Util.ReturnValue("403", "您登录超时或还未登录请<a href='javascript:top.doLogin()'>重新登录</a>!!!!"))
                Response.End()
            End If
        End Sub

        Protected Overrides Sub LogOut(ByVal toUrl As String)

            If AppConfigInfo.AdminSSO Then
                Try
                    Dim tokenService As New adminpassport.TokenService
                    If Not tokenService Is Nothing Then
                        tokenService.ClearToken(Admin.Token)
                        tokenService = Nothing
                    End If

                Catch ex As Exception
                    Response.Write(ex.Message)
                End Try
            End If

            Session.Contents(_USER) = Nothing
            Session.Abandon()

            If Not String.IsNullOrEmpty(toUrl) Then
                Response.Redirect(toUrl)
            End If

            mAdmin = Nothing

            Response.Write(Util.ReturnValue("0", "你已经成功退出系统!"))
            Response.End()
        End Sub

        Protected Overrides Sub redirectTokenUrl()
            If Not String.IsNullOrEmpty(AppConfigInfo.AdminGetTokenPage) Then
                Response.Redirect(getTokenURL(AppConfigInfo.AdminGetTokenPage))
            End If
        End Sub




        Private Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
            mAdmin = Nothing
        End Sub

        Private Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
            mAdmin = Nothing
        End Sub

        REM ******************************************
        Public Function xAdmin(ByVal s As String) As String
            If Not mAdmin.IsLogin Then
                Return String.Empty
            End If
            Return mAdmin.getProperty(s)
        End Function

    End Class

End Namespace
